<template>
  <ul class="todo-main">
    <Item
      v-for="todo in todoList"
      :key="todo.id"
      v-bind="todo"
      @singeCheckedHandle="singeCheckedHandle"
      @singledeleteHandle="singledeleteHandle"
    />
  </ul>
</template>

<script>
import Item from "./Item";
export default {
  name: "List",
  data() {
    return {
      todoList: [],
    };
  },
  components: {
    Item,
  },
  mounted() {
    this.todoList = JSON.parse(localStorage.getItem("todoList") || "[]");
    //1.给$bus绑定从Header获取数据的函数
    this.$bus.$on("getTodo", (value) => {
      // console.log(this, value, "value");
      //Vue中的unshift方法是修改原数组的方法,返回值是一个数字
      this.todoList.unshift(value);
      // console.log(num,'unshift返回值');
    });
    //2.绑定获取footer的checked的值的函数
    this.$bus.$on("getFooterchecked", (e) => {
      // console.log(e);
      this.todoList = this.todoList.map((item) => {
        return { ...item, done: e };
      });
    });
    //3.绑定点击清除已完成的函数
    this.$bus.$on("getDonec hecked", () => {
      this.todoList = this.todoList.filter((item) => !item.done);
    });
  },
  watch: {
    todoList: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.todoList));
        this.$bus.$emit("getAllList", this.todoList);
      },
    },
  },
  methods: {
    singeCheckedHandle(id) {
      this.todoList = this.todoList.map((item) => {
        return item.id === id ? { ...item, done: !item.done } : item;
      });
    },
    singledeleteHandle(id) {
      console.log(id);
      this.todoList = this.todoList.filter((item) => {
        return item.id !== id;
      });
    },
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>